package com.upb.webserver.fisco.contract;

import com.upb.webserver.account.AccountService;
import com.upb.webserver.common.exception.OperationException;
import com.upb.webserver.common.pojo.account.AccountCommon;
import com.upb.webserver.common.pojo.base.BaseResponse;
import com.upb.webserver.common.pojo.fisco.contract.ReqDeployContractVO;
import com.upb.webserver.common.pojo.fisco.contract.ReqSaveContractVO;
import com.upb.webserver.common.pojo.rest.fisco.chainmgr.resp.RespContract;
import com.upb.webserver.common.pojo.rest.fisco.data.resp.RspContractDeployDTO;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.JsonUtils;
import com.upb.webserver.rest.fisco.FiscoChainMgrRestService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.Duration;
import java.time.Instant;
import java.util.List;

@Log4j2
@RestController
@RequestMapping("fisco-contract")
public class FiscoContractController {

    @Autowired
    private FiscoContractService fiscoContractService;
    @Autowired
    private FiscoChainMgrRestService fiscoChainMgrRestService;
    @Autowired
    private AccountService accountService;

    /**
     * @param param
     * @param result
     * @return
     */
    @PostMapping
    public BaseResponse saveContract(@RequestBody @Valid ReqSaveContractVO param, BindingResult result) {
        log.info("start exec method [saveContract]. param:{}", JsonUtils.objToString(param));
        RespContract resp = fiscoContractService.saveContract(param);
        BaseResponse baseResponse = BaseResponse.initSuccess();
        baseResponse.setData(resp);
        log.info("success exec method [saveChainCode]. baseResponse:{}", JsonUtils.objToString(baseResponse));
        log.info("success exec method [saveContract].");
        return baseResponse;
    }


    /**
     * @param chainId
     * @param applicationId
     * @return
     */
    @GetMapping(value = "/list")
    public BaseResponse queryContractList(@RequestParam(value = "chainId") Integer chainId,
                                          @RequestParam(value = "applicationId", required = false, defaultValue = "0") Integer applicationId) {
        log.info("start exec method [queryContractList]. chainId:{} applicationId:{}", chainId, applicationId);
        List<RespContract> list = fiscoContractService.queryContractList(chainId, applicationId);

        log.info("success exec method [queryContractList].");
        log.debug("success exec method [queryContractList]. result:{}", JsonUtils.objToString(list));
        return new BaseResponse(ConstantCode.SUCCESS, list);
    }


    /**
     * deploy contract.
     *
     * @param param
     * @param result
     * @param request
     * @return
     */
    @PatchMapping(value = "/deploy")
    public BaseResponse deployContract(@RequestBody @Valid ReqDeployContractVO param, BindingResult result, HttpServletRequest request) throws OperationException {
        log.info("start exec method [deployContract]. param:{}", JsonUtils.objToString(param));
        AccountCommon accountCommon = accountService.getAccountCommon(request);
        RspContractDeployDTO deployResult = fiscoContractService.deployContract(accountCommon.getPlatform(), accountCommon.getId(), param.getContractId(), param.getSignUserId(), param.getConstructorParams());
        BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS);
        baseResponse.setData(deployResult);
        log.info("success exec method [deployContract]. baseResponse:{}", JsonUtils.objToString(baseResponse));
        return baseResponse;
    }


    /**
     * @param contractId
     * @return
     */
    @PostMapping(value = "/compile/{contractId}")
    public BaseResponse compileByContractId(@PathVariable("contractId") Integer contractId) {
        BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS);
        Instant startTime = Instant.now();
        log.info("start compileByContractId startTime:{} contractId:{}", startTime.toEpochMilli(), contractId);
        RespContract respContract = fiscoChainMgrRestService.compileByContractId(contractId);
        baseResponse.setData(respContract);

        log.info("end compileContract useTime:{}", Duration.between(startTime, Instant.now()).toMillis());
        return baseResponse;
    }

}
